package com.jy.project.controller;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.google.zxing.multi.qrcode.QRCodeMultiReader;
import com.jy.project.domain.User;
import com.jy.project.ex.BizException;
import com.jy.project.util.JwtUtils;
import com.jy.project.util.ServiceResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;

@Controller
@CrossOrigin
@Slf4j
public class FileController {
    @Value("${upload_path}")
    private String imagePathRoot;


    @Value("${img_url}")
    private String imgUrl;

    private volatile boolean isImagePathRoot;

    private volatile boolean isUploadResumePath;

    private static final String[] IMG_TYPE = {"jpg", "png"};

    @PostMapping("/v1/upload")
    @ResponseBody
    public Object fileUpload(MultipartFile fileImage) throws IOException {

        if (fileImage == null) {
            throw new BizException("上传文件不能为空");
        }
        if (!isImagePathRoot) {
            File file = new File(imagePathRoot);
            if (!file.exists()) {
                file.mkdirs();
            }
            isImagePathRoot = false;
        }
        String fileName = fileImage.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
        if (StringUtils.isEmpty(fileType)){
            fileType="jpg";
        }
        String uuid = IdUtil.getSnowflake(1L, 1L).nextIdStr();
        String imageFilePath = imagePathRoot + uuid+"."+fileType;
        fileImage.transferTo(new File(imageFilePath));
        return ServiceResultUtils.success(imgUrl + uuid+"."+fileType);
    }

    @GetMapping(value = "/image/{imageId}", produces = MediaType.IMAGE_JPEG_VALUE)
    public void get(@PathVariable("imageId") String imageId, HttpServletResponse response) throws IOException {
        String path = imagePathRoot + imageId;
        File file = new File(path);
        if (!file.exists()) {
            throw new BizException("404");
        }
        OutputStream os = null;
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(file));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (IOException e) {
            log.error("获取图片异常{}", e.getMessage());
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }

    @PostMapping("/v1/qrcodeUpload")
    @ResponseBody
    public Object qrcodeUpload(@RequestHeader("token") String token, MultipartFile fileImage) throws IOException {
        User user = JwtUtils.verifyToken(token);
        if (user == null) {
            throw new BizException("token出错");
        }
        if (fileImage == null) {
            throw new BizException("上传文件不能为空");
        }
        File file = new File(imagePathRoot);
        if (!file.exists()) {
            file.mkdirs();
        }
        String uuid = IdUtil.getSnowflake(1L, 1L).nextIdStr();
        String imageFilePath = imagePathRoot + uuid;
        File imgfile = new File(imageFilePath);
        fileImage.transferTo(imgfile);
        String url = "";
        try {
            url = QrCodeUtil.decode(imgfile);
        } catch (Exception e) {
            throw new BizException("无法解析二维码");
        } finally {
            imgfile.delete();
        }
        return ServiceResultUtils.success(url);

    }



}


